#
# This file is a part of the open-eBackup project.
# This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
# If a copy of the MPL was not distributed with this file, You can obtain one at
# http://mozilla.org/MPL/2.0/.
#
# Copyright (c) [2024] Huawei Technologies Co.,Ltd.
#
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
#

import json

from common.parse_parafile import ParamFileUtil

from adds.comm.log import log
from adds.comm.utils import convert_copy_id
from adds.comm.param_base import ParamBase


class BackupParam(ParamBase):
    def __init__(self, req_id):
        super().__init__(req_id)
        self._application: dict = dict()
        self._auth_flag = True
        self.parse_param()

    def parse_param(self):
        try:
            self._param = ParamFileUtil.parse_param_windows_file(self.req_id)
        except Exception as err:
            raise Exception(f"Failed to parse job param file for {err}") from err

    def get_repository(self, repository_type):
        repositories = self._param.get("job", {}).get("repositories", [])
        for repository in repositories:
            if repository['repositoryType'] == repository_type:
                return repository
        return {}

    def get_repository_path(self, repository_type):
        repositories_path_list = self.get_repository(repository_type).get("path", [])
        return repositories_path_list[0] if repositories_path_list else ""

    def get_copy_id(self):
        return self._param.get('job').get('copy')[0].get('id')

    def get_repositories(self):
        return self._param.get('job').get('repositories')

    def get_sub_job_info(self):
        job_info_str = self._param.get("subJob", {}).get("jobInfo", '')
        job_info = json.loads(job_info_str) if job_info_str else {}
        return job_info

    def get_sub_job_name(self):
        sub_job_name = self._param.get("subJob", {}).get("jobName", "")
        return sub_job_name

    def get_object_backup_flag(self):
        object_flag = self._param.get("job", {}).get("extendInfo", {}).get("object_backup", '')
        if object_flag == 'true':
            return True
        return False

    def get_backup_path(self, repository_type):
        data_repository_info = self.get_repository(repository_type)
        host_list = data_repository_info.get("remoteHost", [])
        share_name = data_repository_info.get("remoteName")
        target_id = convert_copy_id(self.get_copy_id())
        if host_list and share_name:
            ip = host_list[0].get("ip", "")
            current_path = f"\\\\{ip}\\{share_name}"
            return current_path
        log.error(f"Get backupTarget path faild, share_name: {share_name}, host_list: {host_list}")
        return ""
